package com.lagou.rpc.consumer.proxy;

import com.alibaba.fastjson.JSON;
import com.lagou.rpc.common.RpcRequest;
import com.lagou.rpc.common.RpcResponse;
import com.lagou.rpc.consumer.client.RpcClient;
import com.lagou.rpc.consumer.config.RpcConfig;
import com.lagou.rpc.consumer.utils.SpringUtils;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * 客户端代理类-创建代理对象
 * 1.封装request请求对象
 * 2.创建RpcClient对象
 * 3.发送消息
 * 4.返回结果
 */
public class RpcClientProxy {

    private static RpcClientProxy rpcClientProxy = new RpcClientProxy();

    private RpcConfig rpcConfig;

    private List<RpcClient> rpcClients = new ArrayList<>();

    private int num = 0;

    private RpcClientProxy(){

    }

    public static RpcClientProxy getInstance(){
        return rpcClientProxy;
    }

    public void initClient() throws Exception {
        rpcConfig = SpringUtils.getBean(RpcConfig.class);
        String rpcIps = this.rpcConfig.getRpcIps();
        String rpcPorts = this.rpcConfig.getRpcPorts();
        String[] ips = rpcIps.split(",");
        String[] ports = rpcPorts.split(",");
        if(ips.length != ports.length){
            throw new Exception("配置文件异常,请检查配置文件");
        }
        for (int i = 0; i < ips.length; i++) {
            RpcClient rpcClient = new RpcClient(ips[i], Integer.parseInt(ports[i]));
            rpcClients.add(rpcClient);
        }

    }

    public Object createProxy(Class serviceClass) {
        return Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),
                new Class[]{serviceClass}, new InvocationHandler() {
                    @Override
                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                        //1.封装request请求对象
                        RpcRequest rpcRequest = new RpcRequest();
                        rpcRequest.setRequestId(UUID.randomUUID().toString());
                        rpcRequest.setClassName(method.getDeclaringClass().getName());
                        rpcRequest.setMethodName(method.getName());
                        rpcRequest.setParameterTypes(method.getParameterTypes());
                        rpcRequest.setParameters(args);
                        //2.获取RpcClient对象
                        RpcClient rpcClient = rpcClients.get(num % rpcClients.size());
                        num++;
                        //RpcClient rpcClient = new RpcClient("127.0.0.1", 8899);
                        System.out.println("当前使用的rpc客户端:" + rpcClient.toString());
                        try {
                            //3.发送消息
                            Object responseMsg = rpcClient.send(JSON.toJSONString(rpcRequest));
                            RpcResponse rpcResponse = JSON.parseObject(responseMsg.toString(), RpcResponse.class);
                            if (rpcResponse.getError() != null) {
                                throw new RuntimeException(rpcResponse.getError());
                            }
                            //4.返回结果
                            Object result = rpcResponse.getResult();
                            return JSON.parseObject(result.toString(), method.getReturnType());
                        } catch (Exception e) {
                            throw e;
                        } finally {
                            //rpcClient.close();
                        }

                    }
                });
    }
}
